import { ref, computed, reactive } from "vue";
import { defineStore } from "pinia";
import http from "@/utils/axios.js";
import utils from "@/utils/tree.js";
import { createThumbnail, createImageUrl } from "@/utils/image.js";
// 用户目录树据
const useDirStore = defineStore(
	"dir",
	() => {
		const dirList = ref([{ title: "根目录", id: 0 }]); // 目录列表树
		const treeDate = ref(); //目录转成树后的文件
		const dirFilesTotal = ref({});
		//从服务器上拉取目录树
		function getDirTree(pid, page = 1, limit = 100) {
			page = page * 1;
			return http
				.get("app/pan/dir/select", {
					params: { pid, page, is_count: true, limit },
				})
				.then((res) => {
					const { list, count } = res || {};
					if (!Array.isArray(list)) {
						return;
					}
					if (page === 1) {
						delete dirList.value;
						delete treeDate.value;
						dirList.value = [{ title: "根目录", id: 0 }, ...list];
					} else {
						dirList.value.push(...list);
					}
					if (count > page * limit) {
						return getDirTree(pid, page + 1, limit);
					} else {
						dirList.value.sort((n1, n2) => {
							return n2.id - n1.id;
						});
						treeDate.value = utils.listToTree(dirList.value);
					}
				});
		}
		//  新增目录 title[目录名], pid [当前选中目录ID],插入到当前选中目录下
		function insertDir(title, pid) {
			return http
				.post("app/pan/dir/insert", {
					title,
					pid,
				})
				.then((res) => {
					if (!res) return Promise.reject();
					getDirTree();
				});
		}
		//  修改目录 title[目录名], id [当前选中目录ID],
		function renameDir(title, id) {
			return http
				.post("app/pan/dir/rename", {
					title,
					id,
				})
				.then((res) => {
					if (!res) return Promise.reject();
					const i = dirList.value.findIndex((item) => {
						return item.id === id;
					});
					dirList.value[i].title = res.title;
				});
		}
		// 修改目录文件数量
		function changeDirTotal(dirId, total) {
			dirFilesTotal.value[dirId] = total;
		}
		// 设置目录主图
		function setArticleImage(id, file) {
			const i = dirList.value.findIndex((item) => {
				return item.id === id;
			});
			const path = createImageUrl(file);
			dirList.value[i].path = path;
			http.post("app/pan/dir/setArticleImage", { id, path });
		}
		//清空目录
		function clear() {
			dirList.value.length = 0;
			dirList.value.push([{ title: "根目录", id: 0 }]);
			treeDate.value.length = 0;
		}
		getDirTree();
		return {
			dirList, //目录列表
			treeDate, //目录树
			dirFilesTotal, //目录树文件数量
			getDirTree, //从服务器重新取目录
			insertDir, //插入目录
			renameDir, //重名命目录
			changeDirTotal, //修改目录文件数量
			setArticleImage, //设置文章主图
			clear, //清空目录
		};
	},
	{
		persist: {
			key: "webman-pan-dir",
		},
	}
);
export default useDirStore;
